package edu.zut.cs.network.dao.service.runnable;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;

import org.apache.poi.util.TempFile;

import edu.zut.cs.network.base.BaseMainCase;
import edu.zut.cs.network.dao.service.BookDaoManager;
import edu.zut.cs.network.dao.service.impl.BookDaoManagerImpl;
import edu.zut.cs.network.entity.Book;

public class GetAllRunnable extends BaseMainCase implements Runnable {
	/** 阻塞队列 */
	private BlockingQueue<List<Book>> blockingQueue;
	/** 队列最大长度 */
	private int maxQueueSize = 1024;
	/*每组个数*/
	private int groupSize = 100;
	private static final List<Book> END = new ArrayList<>();

	private String tableName;

	public GetAllRunnable(BlockingQueue<List<Book>> blockingQueue, String tableName) throws SQLException {
		super();
		this.tableName = tableName;
		this.blockingQueue = blockingQueue;
	}

	private void addDataGroup(List<Book> end2) throws Exception {
		while (blockingQueue.size() >= maxQueueSize) {
			TimeUnit.SECONDS.sleep(3);
		}
		blockingQueue.add(end2);
	}

	BookDaoManager bookDao = new BookDaoManagerImpl();

	@Override
	public void run() {
		logger.info(Thread.currentThread().getName() + "thread：");
		List<Book> bookList;
		bookList = bookDao.getALl(tableName);
		/*分离booklist*/
		int arrSize = bookList.size() % groupSize == 0 ? bookList.size() / groupSize : bookList.size() / groupSize + 1;
		for (int i = 0; i < arrSize; i++) {
			List<Book> sub = new ArrayList<>();
			for (int j = i * groupSize; j <= groupSize * (i + 1) - 1; j++) {
				if (j <= bookList.size() - 1) {
					sub.add(bookList.get(j));
				}
			}
			try {
				addDataGroup(sub);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		try {
			addDataGroup(END);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
